14. Exercise: Implement touchMove()

22 15 AAK TouchMove SC V2

Exercise

In this exercise you are going to implement touchMove().

  1. At the class level, add a touchTolerance variable and set it to ViewConfiguration.get(context).scaledTouchSlop.
private val touchTolerance = ViewConfiguration.get(context).scaledTouchSlop
  1. Define the touchMove() method. Calculate the traveled distance (dx, dy), create a curve between the two points and store it in path, update the running currentX and currentY tally, and draw the path. Then call invalidate() to force redrawing of the screen with the updated path.
private fun touchMove() {
   val dx = Math.abs(motionTouchEventX - currentX)
   val dy = Math.abs(motionTouchEventY - currentY)
   if (dx >= touchTolerance || dy >= touchTolerance) {
       // QuadTo() adds a quadratic bezier from the last point,
       // approaching control point (x1,y1), and ending at (x2,y2).
       path.quadTo(currentX, currentY, (motionTouchEventX + currentX) / 2, (motionTouchEventY + currentY) / 2)
       currentX = motionTouchEventX
       currentY = motionTouchEventY
       // Draw the path in the extra bitmap to cache it.
       extraCanvas.drawPath(path, paint)
   }
   invalidate()
}

In more detail, this is what you will be doing in code:

  1. Calculate the distance that has been moved (dx, dy).
  2. If the movement was further than the touch tolerance, add a segment to the path.
  3. Set the starting point for the next segment to the endpoint of this segment.
  4. Using quadTo() instead of lineTo() create a smoothly drawn line without corners. See Bezier Curves.
  5. Call invalidate() to (eventually call onDraw() and) redraw the view.